<template>
  <r-header />
  <main>
    <div class="main1" v-if="!chats?.length">
      <h1>
        具有 <span>拟人化</span> 的问答，解决您头脑里的问题风暴
      </h1>

      <ul>
        <li v-for="item, index in pre" :key="index" @click="selectQuestion(item)">
          {{ item }}
        </li>
      </ul>
    </div>

    <div class="main2" v-else>
      <ul>
        <li v-for="chat, index in chats" :key="index" :ai="chat.ai">
          <div class="head">
            <r-logo hidename v-if="chat.ai" />
            <img v-else src="/assets/千寻.png" />
          </div>
          <p class="content">{{ chat.text }}</p>
        </li>
      </ul>
    </div>

    <footer>
      <button class="new" @click="input = undefined">
        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"
             class="w-4 h-4">
          <path stroke-linecap="round" stroke-linejoin="round"
                d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0l3.181 3.183a8.25 8.25 0 0013.803-3.7M4.031 9.865a8.25 8.25 0 0113.803-3.7l3.181 3.182m0-4.991v4.99">
          </path>
        </svg>
      </button>

      <div class="input">
        <textarea v-model="input" rows="1" placeholder="发消息给AI"></textarea>
        <button @click="chat()" v-if="!streaming">
          <svg stroke="currentColor" fill="none" stroke-width="2" viewBox="0 0 24 24" stroke-linecap="round"
               stroke-linejoin="round" class="h-4 w-4 mr-1" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg">
            <line x1="22" y1="2" x2="11" y2="13"></line>
            <polygon points="22 2 15 22 11 13 2 9 22 2"></polygon>
          </svg>
        </button>
        <button @click="streaming = false" v-else>
          <loading class="wait" title="AI生成中，大约需要一分钟" />
        </button>
      </div>
    </footer>
  </main>

  <!-- 重试弹窗 -->
  <div v-if="showRetryModal" class="modal-overlay" @click="closeRetryDialog">
    <div class="modal-content" @click.stop>
      <div class="modal-header">
        <h3>生成题目失败</h3>
        <button class="close-btn" @click="closeRetryDialog">×</button>
      </div>
      <div class="modal-body">
        <p>{{ retryMessage }}</p>
      </div>
      <div class="modal-footer">
        <button class="btn btn-secondary" @click="closeRetryDialog">取消</button>
        <button class="btn btn-primary" @click="retryRequest">重试</button>
      </div>
    </div>
  </div>
</template>

<script type="text/javascript">

// AI API调用函数 - 通过后端代理
async function sendToAI(text) {
  const url = 'http://localhost:8088/api/ai/chat';
  const options = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      messages: [
        {
          role: "system",
          "content":"你是一个专业的题目生成助手。请严格按照以下JSON格式生成十道选择题，每道题包含问题、4个选项和正确答案，\"useranswer\":返回为空。[{\"id\":1,\"question\":\"问题内容\",\"options\":{\"A\": \"选项A内容\",\"B\": \"选项B内容\",\"C\": \"选项C内容\",\"D\": \"选项D内容\"},\"correctanswer\":\"A\"\"useranswer\":\"\"},{\"id\":2,\"question\":\"问题内容\",\"options\":{\"A\": \"选项A内容\",\"B\": \"选项B内容\",\"C\": \"选项C内容\",\"D\": \"选项D内容\"},\"correctanswer\":\"A\"\"useranswer\":\"\"},{\"id\":3,\"question\":\"问题内容\",\"options\":{\"A\": \"选项A内容\",\"B\": \"选项B内容\",\"C\": \"选项C内容\",\"D\": \"选项D内容\"},\"correctanswer\":\"A\"\"useranswer\":\"\"},{\"id\":4,\"question\":\"问题内容\",\"options\":{\"A\": \"选项A内容\",\"B\": \"选项B内容\",\"C\": \"选项C内容\",\"D\": \"选项D内容\"},\"correctanswer\":\"A\"\"useranswer\":\"\"},{\"id\":5,\"question\":\"问题内容\",\"options\":{\"A\": \"选项A内容\",\"B\": \"选项B内容\",\"C\": \"选项C内容\",\"D\": \"选项D内容\"},\"correctanswer\":\"A\"\"useranswer\":\"\"},{\"id\":6,\"question\":\"问题内容\",\"options\":{\"A\": \"选项A内容\",\"B\": \"选项B内容\",\"C\": \"选项C内容\",\"D\": \"选项D内容\"},\"correctanswer\":\"A\"\"useranswer\":\"\"},{\"id\":7,\"question\":\"问题内容\",\"options\":{\"A\": \"选项A内容\",\"B\": \"选项B内容\",\"C\": \"选项C内容\",\"D\": \"选项D内容\"},\"correctanswer\":\"A\"\"useranswer\":\"\"},{\"id\":8,\"question\":\"问题内容\",\"options\":{\"A\": \"选项A内容\",\"B\": \"选项B内容\",\"C\": \"选项C内容\",\"D\": \"选项D内容\"},\"correctanswer\":\"A\"\"useranswer\":\"\"},{\"id\":9,\"question\":\"问题内容\",\"options\":{\"A\": \"选项A内容\",\"B\": \"选项B内容\",\"C\": \"选项C内容\",\"D\": \"选项D内容\"},\"correctanswer\":\"A\"\"useranswer\":\"\"},{\"id\":10,\"question\":\"问题内容\",\"options\":{\"A\": \"选项A内容\",\"B\": \"选项B内容\",\"C\": \"选项C内容\",\"D\": \"选项D内容\"},\"correctanswer\":\"A\"\"useranswer\":\"\"}]"
        },
        {
          role: "user",
          content: text
        }
      ]
    })
  };

  try {
    const response = await fetch(url, options);
    const data = await response.json();
    
    if (data.code === 200 && data.data && data.data.choices) {
      return data.data;
    } else {
      throw new Error(data.msg || 'API响应格式错误');
    }
  } catch (error) {
    throw error;
  }
}

export default {
  name: "index",
  data() {
    return {
             pre: [
         "Redis的内存淘汰策略",
         "JavaScript的基础知识",
         "英雄联盟打野经济学",
         "SSM三层架构与核心职责",
         "自动化生产条件下可变资本与剩余价值率",
         "光合作的本质与过程",
         "《百年孤独》魔幻现实主义手法解析",
         "哈希表的设计原理与冲突解决策略",
         "制作一套算法与数据结构的题目",
         "创建关于软件工程的测试题",
         "3A游戏的光照渲染技术演进",
         "设计Vue.js前端开发的测试题",
         "开放世界游戏的任务设计框架",
         "生成关于Linux系统的题目",
         "通货膨胀的成因与货币政策传导机制",
         "关于Git版本控制的相关知识",
         "帮我设计一套关于Spring Boot框架的题目，包含依赖注入、AOP面向切面编程、自动配置原理、事务管理等核心知识点",
         "生成关于微服务架构设计的题目，涵盖服务拆分原则、API网关、分布式事务、熔断降级、配置中心等技术要点",
         "帮我设计关于Redis缓存技术的题目，包括数据结构、持久化机制、事务处理、哨兵模式、集群部署、缓存穿透和雪崩解决方案等内容",
         "制作一套关于TensorFlow深度学习框架的机器学习题目，涵盖神经网络、反向传播算法、模型训练与优化、卷积神经网络、循环神经网络、注意力机制等方面"
       ],
      input: '',
      chats: [],
      // 正在回复中，允许点击停止中断回复
      streaming: false,
      // 重试弹窗相关
      showRetryModal: false,
      retryMessage: '',
    }
  },
  computed: {
  },
  methods: {
    setStreamingText(text) {
      this.chats[this.chats.length - 1].text = text;
      // 往下滚动
      document.documentElement.scrollTo(0, document.documentElement.scrollHeight);
    },
    async chat() {
      const c = this.input?.trim();
      if (!c) return;
      
      // 保存用户输入的主题内容，后续传给后端
      const topic = c;
      
      this.streaming = true;
      this.input = '';
      
      try {
        const response = await sendToAI(topic);
        const aiResponse = response.choices[0].text.trimStart();
        
        // 提取total_tokens（AiController返回的）
        const totalTokens = response.total_tokens || 0;
        console.log('AiController返回的total_tokens:', totalTokens);
        
        // 尝试解析AI返回的JSON格式题目数据
        try {
          // 处理markdown代码块格式的JSON
          let jsonString = aiResponse;
          
          // 如果包含markdown代码块标记，提取JSON部分
          if (jsonString.includes('```json')) {
            const jsonMatch = jsonString.match(/```json\s*([\s\S]*?)\s*```/);
            if (jsonMatch && jsonMatch[1]) {
              jsonString = jsonMatch[1].trim();
            }
          } else if (jsonString.includes('```')) {
            // 处理没有json标识的代码块
            const codeMatch = jsonString.match(/```\s*([\s\S]*?)\s*```/);
            if (codeMatch && codeMatch[1]) {
              jsonString = codeMatch[1].trim();
            }
          }
          
          // 尝试修复JSON格式
          let fixedJsonString = jsonString;
          
          // 如果JSON字符串不以[开头，尝试修复
          if (!fixedJsonString.trim().startsWith('[')) {
            const firstBrace = fixedJsonString.indexOf('{');
            if (firstBrace > 0) {
              fixedJsonString = '[' + fixedJsonString.substring(firstBrace);
            }
          }
          
          // 如果JSON字符串不以]结尾，尝试修复
          if (!fixedJsonString.trim().endsWith(']')) {
            const lastBrace = fixedJsonString.lastIndexOf('}');
            if (lastBrace > 0) {
              fixedJsonString = fixedJsonString.substring(0, lastBrace + 1) + ']';
            }
          }
          
          const parsedData = JSON.parse(fixedJsonString);
          
          // 检查是否是数组格式的题目数据
          if (Array.isArray(parsedData)) {
            this.saveQuestionsAndNavigate(parsedData, totalTokens, topic);
            return;
          } else if (parsedData.questions && Array.isArray(parsedData.questions)) {
            this.saveQuestionsAndNavigate(parsedData.questions, totalTokens, topic);
            return;
          }
        } catch (error) {
          // 显示重试提示弹窗
          this.showRetryDialog();
          return;
        }
        
        // 如果数据格式不符合预期，显示重试提示
        this.showRetryDialog();
        
      } catch (error) {
        console.error('AI对话失败:', error);
        this.chats.push({ 
          created: Math.floor(Date.now() / 1000), 
          text: c, 
          ai: false 
        });
        this.chats.push({ 
          created: Math.floor(Date.now() / 1000), 
          text: "抱歉，AI助手暂时无法回复，请检查网络连接后重试。", 
          ai: true 
        });
      } finally {
        this.streaming = false;
      }
    },
    selectQuestion(question) {
      // 点击预设问题时，将问题添加到输入框
      this.input = question;
    },
    async saveQuestionsAndNavigate(questions, totalTokens = 0, topic = '') {
      // 转换题目格式以适配test.vue的数据结构
      const formattedQuestions = questions.map((q, index) => ({
        question: q.question,
        options: [
          q.options.A,
          q.options.B,
          q.options.C,
          q.options.D
        ],
        correct: this.getCorrectAnswerIndex(q.correctanswer || q.correct_answer),
        useranswer: q.useranswer || ""  // 保留useranswer字段
      }));
      
      
      // 保存题目数据到localStorage
      localStorage.setItem("generatedQuestions", JSON.stringify(formattedQuestions));
      
      // 获取用户ID
      const userId = this.$store.state.user?.profile?.id;
      
      // 如果有用户ID，创建试卷记录
      if (userId) {
        try {
          // 将题目数组转换为JSON字符串（原始格式）
          const titleDetailsJson = JSON.stringify(questions);
          
          const response = await fetch('http://localhost:8088/api/test-paper/create', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({
              userId: userId,
              topic: topic,  // 传递用户输入的主题内容
              titleDetails: titleDetailsJson,
              totalTokens: totalTokens  // 使用AiController返回的tokens数量
            })
          });
          
          const result = await response.json();
          
          if (result.code === 200 && result.data) {
            // 保存试卷ID到localStorage
            localStorage.setItem("paperId", result.data.tesrId);
            console.log('试卷创建成功，试卷ID:', result.data.tesrId, ', 初始tokens:', totalTokens, ', 主题:', topic);
          }
        } catch (error) {
          console.error('创建试卷失败:', error);
        }
      }
      
      // 跳转到测试页面
      this.$router.push('/test');
    },
    getCorrectAnswerIndex(correctAnswer) {
      // 将A、B、C、D转换为0、1、2、3
      const answerMap = { 'A': 0, 'B': 1, 'C': 2, 'D': 3 };
      return answerMap[correctAnswer] || 0;
    },
    showRetryDialog() {
      this.retryMessage = 'AI返回的数据格式不正确，无法生成题目。请尝试重新输入或稍后再试。';
      this.showRetryModal = true;
    },
    closeRetryDialog() {
      this.showRetryModal = false;
      this.retryMessage = '';
    },
    retryRequest() {
      this.closeRetryDialog();
      // 重新发送请求
      this.chat();
    }
  },
  mounted() {
  },
}
</script>

<style lang="scss" scoped>
main {
  --max-width: 1280px;

  max-width: var(--max-width);
  margin: 0 auto;
  padding-top: 80px; // 为固定导航栏留出空间
  padding-bottom: 5em;

  .main1 {
    h1 {
      color: #fff;
      text-align: center;
      margin-bottom: 1rem;
      font-size: max(1.1em, 3vw);

      span {
        color: #6366f1;
      }
    }

    ul {
      display: flex;
      flex-wrap: wrap;
      font-size: .875em;
      text-align: center;
      padding: 0 .5em;

      li {
        max-width: 100%;
        min-width: min(290px, 100%);
        flex: 1;
        padding: 1em;
        margin: .5em;
        border-radius: .5em;
        border: 1px solid rgb(255 255 255 / 0.1);
        background-color: rgb(255 255 255 / 0.05);
        color: #9ca3af;
        word-wrap: break-word;
        cursor: pointer;
        transition: all .15s;

        &:hover {
          transform: rotate(6deg);
        }
      }
    }
  }

  .main2 {
    ul {
      color: #fff;
      padding: 0 1em;

      li {
        padding: 1em;
        background-color: #475569;
        border-bottom: 1px solid rgba(0, 0, 0, .1);
        display: flex;
        align-items: flex-start;
        border-radius: .25em;
        margin-bottom: 1em;

        &[ai] {
          flex-direction: row-reverse;
        }

        .head {
          min-width: 3.5em;
          width: 3.5em;

          & > * {
            width: 100%;
          }

          img {
            width: 100%;
            height: auto;
            object-fit: contain;
            border-radius: 50%;
          }
        }

        .content {
          padding: 0 1em;
          line-height: 1.5;
          font-size: 1.25em;
        }
      }
    }
  }

  footer {
    position: fixed;
    bottom: 0;
    padding: 1em;
    width: 100%;
    display: flex;
    // border-top: 1px solid rgb(229 231 235 / 10%);
    background-color: #0f172a;
    max-width: var(--max-width);

    .new {
      color: #fff;
      border: 2px solid #fff;
      border-radius: .5em;
      background-color: #38bdf8;
      padding: 1em;
      display: flex;
      justify-content: center;
      align-content: center;
      margin-right: 1em;
      cursor: pointer;

      svg {
        width: 1.5em;
      }
    }

    .input {
      flex: 1;
      position: relative;
      display: flex;
      background-color: #374151;
      border-radius: .5em;
      padding: .5em 1em;

      textarea {
        width: 100%;
        height: 100%;
        border: none;
        background-color: transparent;
        resize: none;
        color: #fff;
        overflow-y: auto;
        line-height: 1.5;
        font-weight: 500;
        font-size: 1.125em;
        outline: none;
      }

      ::-webkit-scrollbar {
        width: 0;
      }

      button {
        border: none;
        background-color: transparent;
        padding: 0.75em 1em;
        margin: -0.75em -1em -0.75em 0;
        cursor: pointer;
        color: #6b7280;

        // &:hover {
        //   color: #9ca3af;
        //   background-color: #111827;
        // }

        svg {
          width: auto;
          height: 60%;
          margin-top: 6px;
        }

        .wait {
          flex-direction: row;

          ::v-deep b {
            margin: 0 1em;
          }
        }
      }
    }
  }
}

/* 重试弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: #1e293b;
  border-radius: 8px;
  padding: 0;
  max-width: 400px;
  width: 90%;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.3);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px 16px;
  border-bottom: 1px solid #374151;
}

.modal-header h3 {
  margin: 0;
  color: #fff;
  font-size: 18px;
  font-weight: 600;
}

.close-btn {
  background: none;
  border: none;
  color: #9ca3af;
  font-size: 24px;
  cursor: pointer;
  padding: 0;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  color: #fff;
}

.modal-body {
  padding: 20px 24px;
}

.modal-body p {
  margin: 0;
  color: #d1d5db;
  line-height: 1.5;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 24px 20px;
  border-top: 1px solid #374151;
}

.btn {
  padding: 8px 16px;
  border-radius: 6px;
  border: none;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s;
}

.btn-secondary {
  background: #374151;
  color: #d1d5db;
}

.btn-secondary:hover {
  background: #4b5563;
  color: #fff;
}

.btn-primary {
  background: #3b82f6;
  color: #fff;
}

.btn-primary:hover {
  background: #2563eb;
}
</style>